@file:Suppress("DEPRECATION")

package com.csjbot.weedle_auto.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentUris
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.view.Gravity
import android.view.View
import android.widget.*
import butterknife.bindView
import com.csjbot.weedle_auto.R
import com.csjbot.weedle_auto.adapter.FolderAdapter
import com.csjbot.weedle_auto.file.SaveFileStationListener
import com.csjbot.weedle_auto.file.constants_util.Constants
import com.csjbot.weedle_auto.file.constants_util.FileUtil
import com.csjbot.weedle_auto.fragment.bean.AdioCheckBean
import com.csjbot.weedle_auto.fragment.bean.StationBean
import com.csjbot.weedle_auto.util.CharactersUtil
import com.csjbot.weedle_auto.util.Csjlogger
import com.csjbot.weedle_auto.util.DensityUtil
import com.csjbot.weedle_auto.view.BaseDialog
import com.csjbot.weedle_auto.view.SelectPicPopupWindow
import java.io.File

/**
 * Created by chenqi on 8/4/17.
 */

class PrintFragment : BaseFramgent() {
    val scrTextFolder: TextView by bindView(R.id.scr_text_folder)
    val inrTextFolder: TextView by bindView(R.id.inr_text_folder)
    val plateInrTextFolder: TextView by bindView(R.id.plate_inr_text_folder)
    val oaTextFolder: TextView by bindView(R.id.oa_text_folder)
    val touchTextFolder: TextView by bindView(R.id.touch_text_folder)
    val snDownTextFolder: TextView by bindView(R.id.sn_down_text_folder)
    val snUpTextFolder: TextView by bindView(R.id.sn_up_text_folder)
    val button: Button by bindView(R.id.button2)

    private var adapter: FolderAdapter? = null
    private var fileFormat: String? = null//记录文件格式
    private var adioCheckBean: AdioCheckBean? = null
    private var menuWindow: SelectPicPopupWindow? = null
    private val stationBean: StationBean? = null

    override val resureID: Int
        get() = R.layout.print_fragment

    override fun initView(view: View) {
        super.initView(view)
        button.setOnClickListener { v ->
            menuWindow = SelectPicPopupWindow(activity, itemsOnClick)
            //显示窗口
            menuWindow!!.showAtLocation(v,
                    Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
        }
    }

    fun update() {
        adioCheckBean = BaseFramgent.sharePreferenceTools.getModel(Constants.CHECKINFOR, AdioCheckBean::class.java)
        //        stationBean = sharePreferenceTools.getModel(Constants.SLAMSTATIONBEAN,StationBean.class);
        activity.runOnUiThread {
            //                inrTextFolder.setText(adioCheckBean.);
            scrTextFolder.text = adioCheckBean!!.scr_
            //                plateInrTextFolder.setText(adioCheckBean.getPlate_inr_());
            oaTextFolder.text = adioCheckBean!!.oa_
            touchTextFolder.text = adioCheckBean!!.touch_
            snDownTextFolder.text = adioCheckBean!!.sn_down_
            snUpTextFolder.text = adioCheckBean!!.sn_up_
        }
    }

    //为弹出窗口实现监听类
    private val itemsOnClick = View.OnClickListener { v ->
        menuWindow!!.dismiss()
        when (v.id) {
            R.id.email_layout -> {
                emailDialog()
                Csjlogger.info("chenqi email_layout")
            }
            R.id.folder_layout -> {
                folderDialog()
                Csjlogger.info("chenqi folder_layout")
            }
            else -> {
            }
        }
    }

    private fun emailDialog() {
        Toast.makeText(activity, "此功能还没有开放！", 1000).show()
    }

    private fun folderDialog() {
        if (FileUtil.isRootSystem) {
            getDIR()
        } else {
            Toast.makeText(activity, "文件处理失败！\r\n 可能是您的机子没有root", 1000).show()
        }
    }

    /**
     * listView
     */
    fun getDIR() {
        val list = FileUtil.folderList
        val view22 = View.inflate(activity, R.layout.file_folder_list, null)

        val view = view22.findViewById(R.id.file_folder) as ListView

        adapter = FolderAdapter(list, activity)
        view.adapter = adapter
        adapter!!.notifyDataSetChanged()

        val builder = BaseDialog.Builder(activity)
        builder.setTitle(getString(R.string.choice_folder))
        builder.setContentView(view22)

        val dialog = builder.create()
        dialog.show()
        val params = dialog.window!!.attributes
        params.width = activity.windowManager.defaultDisplay.width - DensityUtil.dp2px(activity, 40f)
        params.height = activity.windowManager.defaultDisplay.width - DensityUtil.dp2px(activity, 80f)
        dialog.window!!.attributes = params
        view.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            showSavePath(position)
            dialog.dismiss()
        }
    }

    /**
     * listView
     */
    fun showSavePath(item: Int) {
        val path = FileUtil.getAllPath(adapter!!.getItem(item) as File)
        val file = adapter!!.getItem(item) as File

        val view = View.inflate(activity, R.layout.file_format_dialog, null)

        val textView = view.findViewById(R.id.path_name) as TextView
        val editText = view.findViewById(R.id.path_name_enter) as EditText
        val spinner = view.findViewById(R.id.file_name_ge) as Spinner
        val builder = BaseDialog.Builder(activity)
        builder.setTitle(R.string.is_not_save_file)
        textView.text = getString(R.string.file_path_is) + path
        builder.setCancleEnable(false)
        builder.setContentView(view)

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                fileFormat = resources.getStringArray(R.array.file)[position]
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }

        builder.setNegativeButton(R.string.save, DialogInterface.OnClickListener { dialog, _ ->
            //文件名字
            var fileName = editText.text.toString()
            //如果在相应
            if (fileName.equals(getString(R.string.enter_file_name), ignoreCase = true)) {
                fileName = CharactersUtil.randomChar.toString()
            }

            fileName = fileName + fileFormat!!

            val StringInForAll = stationBean!!.toString() + adioCheckBean!!.toString()

//            Csjlogger.info("chenqi filename {}{}{}", fileName, file, StringInForAll)
//            Csjlogger.info("chenqi filename {}" ,fileName)

            //文件格式
            FileUtil.saveFileToSave(fileName, file, StringInForAll, object : SaveFileStationListener {
                override fun FileNotFound() {
                    Toast.makeText(activity, R.string.save_failed, 1000)
                    dialog.dismiss()
                }

                override fun IOEError() {
                    Toast.makeText(activity, R.string.save_failed, 1000)
                    dialog.dismiss()
                }

                override fun SaveSuccess() {
                    Toast.makeText(activity, R.string.save_success, 1000)
                    showFolder()
                    dialog.dismiss()
                }

                override fun FileIsExists() {
                    Toast.makeText(activity, R.string.file_exists, 1000)
                    dialog.dismiss()
                }
            })
        })

        builder.setPositiveButton(getString(R.string.not_save), DialogInterface.OnClickListener { dialog, _ ->
            dialog.dismiss()
        })
        val dialog = builder.create()
        dialog.show()
    }

    private fun showFolder() {
        if (FileUtil.isRootSystem) {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "*/*"
            intent.addCategory(intent.type)
            startActivityForResult(intent, 1)
        } else {
            Toast.makeText(activity, "文件处理失败！\r\n 可能是您的机子没有root," + FileUtil.isRootSystem, 1000).show()
        }
    }

    internal var path: String? = null

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Csjlogger.info("chenqi onActivityResult{}")
        if (resultCode == Activity.RESULT_OK) {
            val uri = data!!.data
            if ("file".equals(uri.scheme, ignoreCase = true)) {//使用第三方应用打开
                path = uri.path
                //                tv.setText(path);
                //                Toast.makeText(getActivity(), path + "11111", Toast.LENGTH_SHORT).show();
                return
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                path = getPath(activity, uri)
                //                tv.setText(path);
                Toast.makeText(activity, path, Toast.LENGTH_SHORT).show()
            } else {//4.4以下下系统调用方法
                path = getRealPathFromURI(uri)
                //                tv.setText(path);
                //                Toast.makeText(getActivity(), path + "222222", Toast.LENGTH_SHORT).show();
            }
        }
    }


    fun getRealPathFromURI(contentUri: Uri): String? {
        var res: String? = null
        val proj = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = activity.contentResolver.query(contentUri, proj, null, null, null)
        if (null != cursor && cursor.moveToFirst()) {
            val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            res = cursor.getString(column_index)
            cursor.close()
        }
        return res
    }


    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    fun getPath(context: Context, uri: Uri): String? {
        val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                val docId = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val type = split[0]

                if ("primary".equals(type, ignoreCase = true)) {
                    return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                }
            } else if (isDownloadsDocument(uri)) {
                val id = DocumentsContract.getDocumentId(uri)
                val contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(id)!!)
                return getDataColumn(context, contentUri, null, null)
            } else if (isMediaDocument(uri)) {
                val docId = DocumentsContract.getDocumentId(uri)
                val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                val type = split[0]

                var contentUri: Uri? = null
                if ("image" == type) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                } else if ("video" == type) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ("audio" == type) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }

                val selection = "_id=?"
                val selectionArgs = arrayOf(split[1])

                return getDataColumn(context, contentUri, selection, selectionArgs)
            }
        } else if ("content".equals(uri.scheme, ignoreCase = true)) {
            return getDataColumn(context, uri, null, null)
        } else if ("file".equals(uri.scheme, ignoreCase = true)) {
            return uri.path
        }
        return null
    }


    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    fun getDataColumn(context: Context, uri: Uri?, selection: String?,
                      selectionArgs: Array<String>?): String? {

        var cursor: Cursor? = null
        val column = "_data"
        val projection = arrayOf(column)

        try {
            cursor = context.contentResolver.query(uri!!, projection, selection, selectionArgs, null)
            if (cursor != null && cursor.moveToFirst()) {
                val column_index = cursor.getColumnIndexOrThrow(column)
                return cursor.getString(column_index)
            }
        } finally {
            if (cursor != null)
                cursor.close()
        }
        return null
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    fun isExternalStorageDocument(uri: Uri): Boolean {
        return "com.android.externalstorage.documents" == uri.authority
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private fun isDownloadsDocument(uri: Uri): Boolean {
        return "com.android.providers.downloads.documents" == uri.authority
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private fun isMediaDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.authority
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    fun isFolderDocument(uri: Uri): Boolean {
        return "com.android.providers.media.documents" == uri.authority
    }

    override fun onPause() {
        //        Csjlogger.info("chenqi onPause print {}" );
        super.onPause()
    }

    override fun onResume() {
        //        Csjlogger.info("chenqi onResume print {}" );
        super.onResume()
    }

    override fun onDestroyView() {
        //        Csjlogger.info("chenqi onDestroyView print {}" );
        super.onDestroyView()
    }


    override fun onAttach(context: Context?) {
        //        Csjlogger.info("chenqi onAttach print {}" );
        super.onAttach(context)
    }

    override fun onDestroy() {
        //        Csjlogger.info("chenqi onDestroy print {}" );
        super.onDestroy()
    }

    override fun onStart() {
        update()
        super.onStart()
    }

    override fun onStop() {
        //        Csjlogger.info("chenqi onStop print {}" );
        super.onStop()
    }

}
